package com.gitee.connect_screen;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.provider.Settings;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.hardware.display.DisplayManager;

import com.gitee.connect_screen.job.StartFloatingButton;
import com.gitee.connect_screen.shizuku.ServiceUtils;
import com.gitee.connect_screen.shizuku.ShizukuUtils;

public class FloatingButtonService extends Service {
    private WindowManager windowManager;
    private View floatingView;
    private int displayId;
    private float initialX, initialY;
    private float initialTouchX, initialTouchY;
    private static final String PREFS_NAME = "FloatingButtonPrefs";
    private static final String KEY_X = "button_x";
    private static final String KEY_Y = "button_y";
    private static final int FADE_DELAY = 5000; // 5秒
    private Runnable fadeOutRunnable;
    private android.os.Handler handler;
    private boolean isReady = true;
    private static final long DOUBLE_CLICK_TIME_DELTA = 300; //双击间隔时间（毫秒）
    private long lastClickTime = 0;

    public static boolean startFloating(Context context, int displayId, boolean dryRun) {
        // 检查悬浮窗权限
        if (!Settings.canDrawOverlays(context)) {
            if (dryRun) {
                return false;
            }
            // 请求悬浮窗权限
            Intent intent = new Intent(
                    Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                    Uri.parse("package:" + context.getPackageName())
            );
            context.startActivity(intent);
            return false;
        }

        if (ShizukuUtils.hasShizukuStarted()) {
            if (!dryRun) {
                State.startNewJob(new StartFloatingButton(displayId, context));
            }
            return true;
        }

        // 检查无障碍服务权限并尝试启动服务
        if (!TouchpadAccessibilityService.isAccessibilityServiceEnabled(context)) {
            if (!dryRun) {
                Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
                context.startActivity(intent);
            }
            return false;
        }

        if (dryRun) {
            return true;
        }
        // 启动无障碍服务
        Intent serviceIntent = new Intent(context, TouchpadAccessibilityService.class);
        context.startService(serviceIntent);

        // 延迟1秒后启动触控板
        new Handler().postDelayed(() -> {
            if (TouchpadAccessibilityService.getInstance() == null) {
                Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
                context.startActivity(intent);
            } else {
                Intent serviceIntent2 = new Intent(context, FloatingButtonService.class);
                serviceIntent2.putExtra("display_id", displayId);
                context.startService(serviceIntent2);
            }
        }, 1000);
        return true;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        State.floatingButtonService = this;
        if (intent != null) {
            displayId = intent.getIntExtra("display_id", -1);
            if (displayId != -1) {
                if (floatingView != null) {
                    this.onDestroy();
                }
                createFloatingButton();
            }
        }
        return START_STICKY;
    }

    public void onDisplayRemoved(int displayId) {
        if (this.displayId == displayId) {
            stopSelf();
        }
    }

    public void onSingleAppLaunched() {
        resetButtonVisibility();
    }

    private void createFloatingButton() {
        handler = new android.os.Handler();
        fadeOutRunnable = new Runnable() {
            @Override
            public void run() {
                fadeOutButton();
            }
        };

        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        floatingView = LayoutInflater.from(this).inflate(R.layout.floating_back_button, null);
        ImageView backButton = floatingView.findViewById(R.id.floating_back_image);
        backButton.setImageResource(R.drawable.ic_back);

        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT
        );
        params.gravity = Gravity.TOP | Gravity.START;
        
        // 读取上次保存的位置
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        params.x = prefs.getInt(KEY_X, 0);
        params.y = prefs.getInt(KEY_Y, 100);
        if (params.x < 0) {
            params.x = 0;
        }
        if (params.y < 0) {
            params.y = 0;
        }

        // 获取目标显示器的 WindowManager
        DisplayManager displayManager = (DisplayManager) getSystemService(Context.DISPLAY_SERVICE);
        Display display = displayManager.getDisplay(displayId);
        if (display == null) {
            stopSelf();
            return;
        }

        // 使用正确的显示器上下文建 WindowManager
        Context displayContext = createDisplayContext(display);
        windowManager = (WindowManager) displayContext.getSystemService(Context.WINDOW_SERVICE);

        try {
            windowManager.addView(floatingView, params);
            State.log("添加悬浮窗于 (" + params.x + "," + params.y + ")");
        } catch (Exception e) {
            State.log("添加悬浮窗失败: " + e.getMessage());
            stopSelf();
            return;
        }

        // 添加触摸事件处理
        floatingView.setOnTouchListener((v, event) -> {
            // 触摸时重置透明度
            resetButtonVisibility();

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    initialX = params.x;
                    initialY = params.y;
                    initialTouchX = event.getRawX();
                    initialTouchY = event.getRawY();
                    return true;

                case MotionEvent.ACTION_MOVE:
                    params.x = (int) (initialX + (event.getRawX() - initialTouchX));
                    params.y = (int) (initialY + (event.getRawY() - initialTouchY));
                    windowManager.updateViewLayout(floatingView, params);
                    return true;

                case MotionEvent.ACTION_UP:
                    if (Math.abs(event.getRawX() - initialTouchX) < 10
                            && Math.abs(event.getRawY() - initialTouchY) < 10) {
                        long clickTime = System.currentTimeMillis();
                        if (clickTime - lastClickTime < DOUBLE_CLICK_TIME_DELTA) {
                            TouchpadActivity.launchLastPackage(this, displayId);
                            lastClickTime = 0; // 重置最后点击时间
                        } else {
                            // 单击事件
                            if (!isReady) {
                                resetButtonVisibility();
                            } else {
                                TouchpadActivity.performBackGesture(ServiceUtils.getInputManager(), displayId);
                            }
                            lastClickTime = clickTime;
                        }
                    } else {
                        // 保存新的位置
                        SharedPreferences.Editor editor = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).edit();
                        editor.putInt(KEY_X, params.x);
                        editor.putInt(KEY_Y, params.y);
                        editor.apply();
                    }
                    return true;
            }
            return false;
        });

        // 初始启动淡出计时器
        startFadeOutTimer();
    }

    private void startFadeOutTimer() {
        handler.removeCallbacks(fadeOutRunnable);
        handler.postDelayed(fadeOutRunnable, FADE_DELAY);
    }

    private void fadeOutButton() {
        floatingView.animate()
                .alpha(0.0f)
                .setDuration(500)
                .withEndAction(new Runnable() {
                    @Override
                    public void run() {
                        isReady = false;
                    }
                })
                .start();
    }

    private void resetButtonVisibility() {
        handler.removeCallbacks(fadeOutRunnable);
        floatingView.animate()
                .alpha(1.0f)
                .setDuration(200)
                .withEndAction(new Runnable() {
                    @Override
                    public void run() {
                        isReady = true;
                    }
                })
                .start();
        startFadeOutTimer();
    }

    @Override
    public void onDestroy() {
        if (handler != null) {
            handler.removeCallbacks(fadeOutRunnable);
        }
        super.onDestroy();
        if (floatingView != null && windowManager != null) {
            windowManager.removeView(floatingView);
            floatingView = null;
        }
        State.floatingButtonService = null;
    }

    public void onDisplayChanged(int displayId) {
        if (this.displayId == displayId) {
            resetButtonVisibility();
        }
    }
}